<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\Order;
use App\Services\PayService;
use Illuminate\Http\Request;

class WxPayController extends ApiController
{
    protected $payService;
    public function __construct(PayService $payService)
    {
        $this->payService = $payService;
    }

    /**
     * 支付回调
     */
    public function WxPayNotify()
    {
        $pay = $this->payService->getPay();
        $response = $pay->handlePaidNotify(function ($message, $fail) {
            // 你的逻辑
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {

                    $this->payService->payAfter($message);
                    return true;
                    // 用户支付失败
                } else if (array_get($message, 'result_code') === 'FAIL') {
                    // $order->status = 'paid_fail';
                    return $fail('支付失败');
                }
                return true;
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
        return $response;
    }

}
